<template>
  <GcTable
    v-loading="loading"
    v-model:searchKeywords="searchKeywords"
    :pagination="pagination"
    :columns="USER_MANAGE_COLUMNS"
    :tableData="tableData"
    :filterList="filterList"
    :defaultFilter="defaultFilter"
    searchPlaceholder="请输入昵称/邮箱/手机号进行搜索"
    @current-change="handlerCurrentChange"
    @search="handlerSearch"
    @get-search-params="getSearchParams"
    @reset-fileds="resetSearchParams">
    <template #gender="{ row }">{{ row.gender === '0' ? '女' : row.gender === '1' ? '男' : '未知' }}</template>
    <template #avatar="{ row }">
      <el-image
        v-if="row.avatar"
        :z-index="999999"
        preview-teleported
        style="width: 30px; height: 30px"
        :src="row.avatar"
        :zoom-rate="1.2"
        :preview-src-list="[row.avatar]"
        fit="cover"
      />
    </template>
    <template #status="{ row }">
      <el-switch
        :disabled="!hasPermission('user-list-manage-permission:btn:edit')"
        :key="row.id"
        v-model="row.status"
        active-value="1"
        inactive-value="0"
        active-text="启用"
        inactive-text="禁用"
        inline-prompt
        :width="52"
        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        @change="handleUpdateUserStatus($event, row)"
      />
    </template>
    <template #bindPassword="{ row }">
      <span
        :class="[!row.bindPassword ? 'text-error' : 'text-success']">
        {{ !row.bindPassword ? '否' : '是' }}
      </span>
    </template>
    <template #bindwx="{ row }">
      <span
        :class="[!row.bindwx ? 'text-error' : 'text-success']">
        {{ !row.bindwx ? '否' : '是' }}
      </span>
    </template>
    <template #operate="{ row }">
      <div class="operate-btn-group center">
        <gc-icon-button
          v-permission="'user-list-manage-permission:btn:edit'"
          type="link"
          @click="currentUserInfo = row; userVisible = true">编辑</gc-icon-button>
      </div>
    </template>
  </GcTable>
  <OperateUserModal
    v-if="userVisible"
    @close-modal="closeModal"
    :userInfo="currentUserInfo" />
</template>

<script setup lang="ts" name="UserList">
import { hasPermission } from '@/directives/permission'
import { ref, reactive } from 'vue'
import { USER_MANAGE_COLUMNS } from './const'
import usePagination from '@/hooks/usePagination'
import type { User } from '@/http/type'
import type { Pagination } from '@/@type'
import { apiGetUserList, apiUpdateUserStatus } from '@/http/service'
import OperateUserModal from './components/OperateUserModal.vue'

interface ResponseUser extends Pagination {
  dataList: Array<User>
}
interface AdvanceSearch {
  username: string
  nickname: string
  email: string
  tel: string
  status: string
  createTime: null | Array<string>
}

const { pagination, loading } = usePagination()
const tableData = ref<Array<User>>([])
const searchKeywords = ref('')
const userVisible = ref(false)
const currentUserInfo = ref<null | User>(null)
const filterList = [
  {
    name: '用户名',
    key: 'username',
    type: 'input' as const,
    placeholder: '请输入用户名（模糊搜索）'
  },
  {
    name: '昵称',
    key: 'nickname',
    type: 'input' as const,
    placeholder: '请输入邮箱（模糊搜索）'
  },
  {
    name: '邮箱',
    key: 'email',
    type: 'input' as const,
    placeholder: '请输入邮箱（模糊搜索）'
  },
  {
    name: '手机号',
    key: 'tel',
    type: 'input' as const,
    placeholder: '请输入手机号（模糊搜索）'
  },
  {
    name: '状态',
    key: 'status',
    type: 'select' as const,
    placeholder: '请选择用户状态',
    options: [
      { value: '0', label: '禁用' },
      { value: '1', label: '启用' }
    ]
  },
  {
    name: '注册时间',
    key: 'createTime',
    type: 'date' as const,
    placeholder: '请选择开始时间',
    dateType: 'datetimerange' as const,
    format: 'YYYY-MM-DD HH:mm:ss',
    valueFormat: 'YYYY-MM-DD HH:mm:ss'
  }
]
const defaultFilter = reactive<AdvanceSearch>({
  username: '',
  nickname: '',
  email: '',
  tel: '',
  status: '',
  createTime: null
})

/**
 * 用户列表查询
 */
async function findMemberList () {
  const searchParams = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    searchKeywords: searchKeywords.value,
    ...defaultFilter,
    startTime: defaultFilter.createTime ? defaultFilter.createTime[0] : null,
    endTime: defaultFilter.createTime ? defaultFilter.createTime[1] : null
  }
  loading.value = true
  try {
    const { dataList, ...pageInfo } = await apiGetUserList<ResponseUser>(searchParams)
    tableData.value = dataList
    Object.assign(pagination, pageInfo)
  } catch (error) {
    tableData.value = []
  } finally {
    loading.value = false
  }
}
findMemberList()

/**
 * 修改用户当前状态
 * @param status
 * @param rowItem
 */
async function handleUpdateUserStatus (status: string, rowItem: User) {
  if (!rowItem.id) return
  try {
    await apiUpdateUserStatus({
      id: rowItem.id,
      status
    })
  } catch (error) {
    rowItem.status = status === '1' ? '0' : '1'
  }
}

function handlerSearch () {
  pagination.pageNo = 1
  findMemberList()
}

function handlerCurrentChange (val: number) {
  pagination.pageNo = val
  findMemberList()
}

function getSearchParams (searchParams: AdvanceSearch) {
  Object.assign(defaultFilter, searchParams)
  findMemberList()
}

function resetSearchParams (searchParams: AdvanceSearch) {
  searchKeywords.value = ''
  Object.assign(defaultFilter, searchParams)
  findMemberList()
}

function closeModal (update?: boolean) {
  if (update) {
    findMemberList()
  }
  userVisible.value = false
}
</script>

<style lang="scss" scoped></style>
